package com.gym.core.json;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;

import com.fasterxml.jackson.databind.DeserializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;

/**
 * json bean convert utils
 * support jaxb annotation
 * @author xinchun.wang 
   @email: 532002108@qq.com
 * @createTime 2015-1-6 下午4:48:03
 */
public class JacksonJsonUtils {

    private static Logger logger = LoggerFactory.getLogger(JacksonJsonUtils.class);
    private static ObjectMapper mapper = new ObjectMapper();
    private static JsonFactory jsonFactory = mapper.getFactory();
    
    /**
     * support jaxb annotation
     */
    static {
    	JaxbAnnotationModule module = new JaxbAnnotationModule();
    	mapper.registerModule(module);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    
    public static String toJson(Object bean) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
        	JsonGenerator jsonGenerator = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
			jsonGenerator.writeObject(bean);
		} catch (IOException e) {
			logger.error("bean2Json error : ",e);
		}
        return new String(out.toByteArray());
    }

    public static <T> List<T> toBeanList(String jsonStr, TypeReference<List<T>> reference) throws IOException {
        return mapper.readValue(jsonStr, reference);
    }
    
    public static <T> T toBean(String jsonStr, TypeReference<T> reference) throws IOException {
        return mapper.readValue(jsonStr, reference);
    }
    
    public static <T> T toBean(String json,Class<T> c) {
    	try {
			return mapper.readValue(json, c);
		}catch (IOException e) {
			logger.error("json2Bean error : ",e);
		}
    	return null;
    }



	public static ObjectMapper getMapper() {
		return mapper;
	}

    

}
